# coding: utf-8
import json
from typing import List, Union

from PIL.ImageQt import QImage
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QVBoxLayout, QWidget, QHBoxLayout
from qfluentwidgets import SubtitleLabel, HyperlinkLabel

from common import LENOVO_USER_AGENT, signalBus
from components import AccordionWidget, AccordionCard, ZoomImageLabel, GridLayout, Alert
from ..base import BaseInterface, WallpaperCard


class ItemWidget(QWidget):
    moreSignal = Signal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.verticalLayout = QVBoxLayout(self)
        self.horizontalLayout = QHBoxLayout()
        self.titleLabel = SubtitleLabel(self)
        self.moreBtn = HyperlinkLabel('更多', self)
        self.gridLayout = GridLayout()
        self.lazyWidgets = []  # type: Union[List[QWidget], List[ZoomImageLabel]]

        self.gridLayout.setVerticalSpacing(11)
        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.addWidget(self.titleLabel)
        self.horizontalLayout.addStretch()
        self.horizontalLayout.addWidget(self.moreBtn)
        self.horizontalLayout.addSpacing(30)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout.addSpacing(20)
        self.verticalLayout.addLayout(self.gridLayout)

        self.moreBtn.clicked.connect(self.moreSignal)

    def title(self):
        return self.titleLabel.text()

    def setData(self, data: dict):
        self.titleLabel.setText(data.get('title'))
        dataList = data.get('dataList', [])
        for item in dataList:
            wallpaperList = item.get('wallpaperList', [])
            for wallpaper in wallpaperList:
                wallpaperImgs = wallpaper.get('wallpaperImg', [])
                uri = wallpaperImgs[0].get('uri', '')
                imgRemark = wallpaperImgs[0].get('imgRemark', '')
                label = WallpaperCard(self)
                label.setDataSrc(uri)
                label.setMinimumSize(270, 180)
                max_url = wallpaper.get('wallpaperImg')[-1]['uri']

                label.setTitle(imgRemark)
                label.setMaxUrl(max_url)

                tags = wallpaper.get('tags') or []
                desc = ','.join([tag['tagName'] for tag in tags])
                label.setDescription(desc)
                label.setMenuData([(wall.get('resolution', ''), wall.get('uri', '')) for wall in wallpaperImgs])
                self.gridLayout.addWidget(label)
                self.lazyWidgets.append(label)

    def setLazyVisible(self, load: bool):
        for widget in self.lazyWidgets:
            widget: ZoomImageLabel
            if load:
                if widget.isNull():
                    widget.setUrl(widget.dataSrc, headers={'user-agent': LENOVO_USER_AGENT})
            else:
                if not widget.isNull():
                    widget.setImage(QImage())


class LenovoBaseInterface(BaseInterface):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.currentIndex = 0
        self.groupContent = []  # type: List[dict]

        self.verticalLayout = QVBoxLayout(self.widget())
        self.accordionWidget = AccordionWidget(self)

        self.__initWidgets()

    def __initWidgets(self):
        self.accordionWidget.setFixedHeight(240)
        self.verticalLayout.setContentsMargins(0, 0, 11, 0)
        self.verticalLayout.setSpacing(20)
        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.addWidget(self.accordionWidget)

    def onBanner(self, result: dict):
        if result.get('status') == 0:
            data = result.get('data')
            dataList = data.get('dataList')
            for item in dataList:
                contentImg = item.get('contentImg', '')
                if contentImg.endswith('.gif'):
                    continue
                card = AccordionCard(self.accordionWidget)
                card.setMaximumWidth(640)
                card.setThumbnail(False)
                card.setUrl(contentImg)
                rankId = json.loads(item.get('targetContent'))['rankId']
                card.clicked.connect(lambda rid=rankId: signalBus.lenovoRankMoreSignal.emit(rid))
                self.accordionWidget.addCard(card)
        else:
            message = result.get('message')
            print(message)
            Alert.error(message)

    def onGroupContent(self, result: dict):
        if result.get('status') == 0:
            data = result.get('data')
            self.groupContent = data
            self.__loadGroupContent()
        else:
            message = result.get('message')
            print(message)
            Alert.error(message)

    def __loadGroupContent(self):
        for item in self.groupContent[self.currentIndex:self.currentIndex + 4]:
            card = ItemWidget(self.widget())
            card.setData(item)
            rankId = json.loads(item.get('targetContent'))['rankId']
            card.moreSignal.connect(lambda rid=rankId: signalBus.lenovoRankMoreSignal.emit(rid))
            self.verticalLayout.addWidget(card)
            self.lazyWidgets.append(card)
            self.currentIndex += 1
        self.lazyTimerStart()

    def nextPage(self):
        self.__loadGroupContent()

    def clear(self):
        for widget in self.lazyWidgets:
            self.verticalLayout.removeWidget(widget)
            widget.deleteLater()
        self.currentIndex = 0
        self.groupContent = []
        self.lazyWidgets = []
        self.accordionWidget.clear()
